package com.example.myapplication6;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.myapplication6.bean.Product;

import java.util.ArrayList;

public class ShoppingActivity extends AppCompatActivity {

  private ListView listView;
  private TextView totalTextView;
  private Button checkoutButton;
  private ArrayList<Product> productList;
  private ArrayAdapter<Product> productAdapter;
  private ArrayList<Product> cartList;
  private ArrayAdapter<Product> cartAdapter;
  private double total = 0.0;

  @SuppressLint("MissingInflatedId")
  @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      listView = findViewById(R.id.listView);
      totalTextView = findViewById(R.id.totalTextView);
      checkoutButton = findViewById(R.id.checkoutButton);

      productList = new ArrayList<Product>();
      productList.add(new Product("Product 1",10.0));
      productList.add(new Product("Product 2",20.0));
      productList.add(new Product("Product 3",30.0));
      productList.add(new Product("Product 4",40.0));
      productList.add(new Product("Product 5",50.0));
      productAdapter = new ArrayAdapter<Product>(this, android.R.layout.simple_list_item_1,productList);
      listView.setAdapter(productAdapter);

      cartList = new ArrayList<Product>();
      cartAdapter = new ArrayAdapter<Product>(this, android.R.layout.simple_list_item_1,cartList);

      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
              Product product = productAdapter.getItem(i);
              cartList.add(product);
              cartAdapter.notifyDataSetChanged();
              totalTextView.setText("Total:$"+ total);
          }
      });
      checkoutButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if (cartList.isEmpty()){
                  Toast.makeText(ShoppingActivity.this,"Your cart is empty", Toast.LENGTH_SHORT).show();
              } else {
                  Toast.makeText(ShoppingActivity.this,"Thank you for your purchase!",Toast.LENGTH_SHORT).show();
                  cartList.clear();
                  cartAdapter.notifyDataSetChanged();
                  total = 0.0;
                  totalTextView.setText("Total: $" + total);
              }
          }
      });
  }
}